package org.sean.framework.web.filter;

import org.sean.framework.util.IOUtil;
import org.sean.framework.util.StringUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * XSS过滤处理
 *
 * @since 1.0.0
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    // body 修改后content-length不对应,body读取有问题
    private long contentLength = -1;

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public int getContentLength() {
        return (int) getContentLengthLong();
    }

    @Override
    public long getContentLengthLong() {
        if (contentLength > -1) {
            return contentLength;
        }
        return super.getContentLengthLong();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        //非json类型，直接返回
        String contentType = super.getHeader(HttpHeaders.CONTENT_TYPE);
        if (StringUtil.isNotEmpty(contentType) && !contentType.toLowerCase().contains(MediaType.APPLICATION_JSON_VALUE)) {
            return super.getInputStream();
        }

        //为空，直接返回
        String json = IOUtil.toString(super.getInputStream(), StandardCharsets.UTF_8);
        if (StringUtil.isBlank(json)) {
            return super.getInputStream();
        }

        //xss过滤
        json = xssEncodeJson(json);
        contentLength = json.getBytes().length;
        final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {
                return bis.read();
            }
        };
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(xssEncode(name));
        if (StringUtil.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] parameters = super.getParameterValues(name);
        if (parameters == null || parameters.length == 0) {
            return new String[0];
        }

        for (int i = 0; i < parameters.length; i++) {
            parameters[i] = xssEncode(parameters[i]);
        }
        return parameters;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> map = new LinkedHashMap<>();
        Map<String, String[]> parameters = super.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
            String[] values = entry.getValue();
            for (int i = 0; i < values.length; i++) {
                values[i] = xssEncode(values[i]);
            }
            map.put(entry.getKey(), values);
        }
        return map;
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(xssEncode(name));
        if (StringUtil.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }

    private String xssEncode(String input) {
        return XssUtils.filter(input);
    }

    private String xssEncodeJson(String input) {
        return XssUtils.filterJson(input);
    }

}
